package com.lovo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lovo.psc.entity.UserBean;

import java.util.Date;
import java.util.HashMap;

public class PscToKen {

    private static final long EXPIRE_TIME = 1000 * 60 * 60;
    private static final String TOKEN_SECRET = "j186";

    public static String createToken(UserBean userBean) {

        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名
        String token = JWT.create().withHeader(header)
                .withClaim("commoduser", userBean.getCommoduser())
                .withClaim("name", userBean.getName())
                .withClaim("number", userBean.getNumber())
                .withExpiresAt(date).sign(algorithm);
        return token;
    }

    public static UserBean verifierJwt(String token) {
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        UserBean userBean = new UserBean();
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {
            DecodedJWT jwt = verifier.verify(token); //认证token
            userBean.setCommoduser(jwt.getClaim("commoduser").asString());
            userBean.setName(jwt.getClaim("name").asString());
            userBean.setNumber(jwt.getClaim("number").asString());

        } catch (Exception e) {
            return userBean;
        }
        return userBean;
    }
}
